const compression = require('compression')
const express = require('express')
const axios = require('axios')
const query = require('./query')
const morgan = require('morgan')
const { getToken } = require('./token')
const cors = require('cors')
const router = require('./router')
const { SUCCESS_RESPONSE } = require('./config/constant')

const app = express()
app.use(compression({ filter: shouldCompress }))

function shouldCompress(req, res) {
  if (req.headers['x-no-compression']) {
    // don't compress responses with this request header
    return false
  }

  // fallback to standard filter function
  return compression.filter(req, res)
}

// 请求日志
app.use(morgan('tiny'))

app.use(cors())

// app.use(虚拟路径,资源目录)
app.use('/uploads/', express.static('./uploads/'))

// 解析表单请求体 application/json
app.use(express.json())
// 解析表单请求体 application/x-www-form-urlencoded，extended: true 允许包含任何数据类型
app.use(express.urlencoded({ extended: true }))

app.use('/', router)

// 一键登录获取OpenId
app.post('/wx/getOpenid', async (req, res) => {
  let code = req.body.code
  let appid = 'wx16b0d75958e59a38'
  let appSecret = 'f2dceb932d90202868bfb23d277825cb'
  let wxAPI = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
  let { data } = await axios.get(wxAPI)
  let { openid } = data
  // 去数据库查询是否有此账户
  let sql = `select user_id,openid from users where openid = '${openid}' limit 1`
  let usersResult = await query(sql)
  if (usersResult.length === 0) {
    // 如果没有则向数据库插入数据
    let sql2 = `insert into users(openid) values('${openid}')`
    await query(sql2)
  }
  const token = getToken({ openid }, '10d')
  res.json(SUCCESS_RESPONSE('登录成功', token))
})

// 获取access_token
app.post('/wx/get_access_token', async (req, res) => {
  let appid = 'wx16b0d75958e59a38'
  let appSecret = 'f2dceb932d90202868bfb23d277825cb'
  let wxAPI = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`
  let { data } = await axios.get(wxAPI)
  res.json(data)
})

// 获取手机号
app.post('/wx/getPhoneNumber', async (req, res) => {
  // 小程序通过wx.login()获取code，调用此接口
  let code = req.body.code
  let access_token = req.body.access_token
  let wxAPI = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${access_token}`
  let { data } = await axios.post(wxAPI, { code })
  res.json(data)
})

app.listen(5000, () => {
  console.log('server is running at port 5000')
})
